--- 新天科技modbus 9600,N,8,1
module(..., package.seeall)

local logtag = "XT_MOD"
local dtu, udtu, addr= {}, {} , 1 -- 配置文件
local meter_ins ,meter_val
function setDtu(_dtu, _udtu)
    dtu, udtu = _dtu, _udtu
    if udtu and tonumber(udtu.dtype) == 9 then sys.taskInit(init) end
end
-- 瞬时:010300000002C40B float
-- 累计:01030008000245C9 long 单位L
local function _pro(d) 
    local _, ins = pack.unpack(d:sub(6, 7)..d:sub(4, 5), ">f")
    meter_ins = string.format("%.2f", ins)
    local v_hex = d:sub(22, 23)..d:sub(20, 21)
    meter_val = tonumber(v_hex:toHex(), 16)/1000
    usrdata.update({meter_val, meter_ins})
    if lcd.LCD_DATA[3]:match('累计(.+)') then
        lcd.LCD_DATA[3] ='流量:' .. (meter_ins or "NULL")
        return
    end
    lcd.LCD_DATA[3] ='累计:' .. (meter_val or "NULL")
end
function init()
    power.openBoost()
    sys.wait(200)
    if udtu.addr and tonumber(udtu.addr) then
        addr = tonumber(udtu.addr)
    end
	while true do
        tools.modbus_send(3,addr,3,0,10)
        local result, data = sys.waitUntil("UART_READ_DONE_NEXT_3" , 5000)
        if result then
            if data then
                _pro(data)
            end
            sys.wait(5000)
        else
            lcd.LCD_DATA[3] = "XTSBC READ TIMEOUT"
        end
	end
end
